<template>
  <div class="app-container">

    <el-row :gutter="10">

      <el-col :span="24">

        <!-- 表格-条件筛区域  -->
        <div class="filter-container">
          <el-input v-model="searchParam.SEARCH_LIKE_username" placeholder="请输入名称" style="width: 200px;"
                    class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 筛选
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary"
                     icon="el-icon-edit" @click="handleCreate"> 新增
          </el-button>
        </div>

        <!-- 表格-内容区域 -->
        <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
                  style="width: 100%;">

          <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                           :width="column.width" :align="column.align?column.align:'center'"
                           :min-width="column.minWidth"
                           :sortable="column.sortable" :fixed="column.fixed" :type="column.type"
                           :formatter="column.formatter">
            <template slot-scope="scope">
              <img v-if="column.imgFlag === true && scope.row[column.prop]"
                   :src=" scope.row[column.prop].indexOf('http') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
                   width="60" height="60" class="img"/>
              <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" >
                编辑
              </el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)" >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 表格-页脚区域 -->
        <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                    :limit.sync="pageRequest.pageSize" @pagination="getList"/>

      </el-col>
    </el-row>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
               width="60%" top="5vh">
      <el-form ref="dataForm" :model="dataForm" :rules="dataFormRules" label-width="140px">

        <el-form-item label="登录名" prop="username">
          <el-input v-model="dataForm.username" size="mini" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="dataForm.realname" size="mini" auto-complete="off"/>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input  v-model="dataForm.phone" size="mini" auto-complete="off"/>
        </el-form-item>

        <el-form-item label="初始密码" prop="password" v-if="operation">
          <el-input v-model="dataForm.password" size="mini" auto-complete="off"/>
        </el-form-item>

        <el-form-item label="用户角色" prop="roleIds">
          <el-select v-model="dataForm.roleIds" placeholder="请选择" size="mini" style="width: 100%" multiple  :multiple-limit="1">
            <el-option v-for="item in roleList" :key="item.value" :label="item.text" :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <cm-upload v-model="dataForm.avatar"></cm-upload>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="dataForm.sex" @change="changeSkuType()">
            <el-radio-button :label="1">男</el-radio-button>
            <el-radio-button :label="0">女</el-radio-button>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="邮箱">
          <el-input v-model="dataForm.email" size="mini" auto-complete="off"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button :loading="editLoading" size="mini" type="primary" @click.native="saveFormData()">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import CmUpload from '@/components/CmUpload' // 上传图片组件引入
import permission from '@/directive/permission/index.js'
import {options} from "runjs"; // 权限判断指令

export default {
  name: 'SystemUser',
  components: {Pagination, CmUpload},
  directives: {waves, permission},
  filters: {},
  data() {
    return {
      // 数据源---组织机构树
      organData: [],
      // 树形结构---默认属性值设置
      defaultProps: {
        children: 'children',
        label: 'deptName'
      },
      tableKey: 0,
      tableList: [], // 表格数据源
      tableTotal: 0, // 表格总条数数据
      listLoading: true,
      pageRequest: {pageNum: 1, pageSize: 10},
      searchParam: {SEARCH_LIKE_username: '', SEARCH_EQ_organ_id: ''},
      columns: [
        {prop: 'username', label: '用户名', minWidth: 120, sortable: false},
        {prop: 'realname', label: '真实姓名', minWidth: 80, sortable: false},
        {prop: 'sex', label: '性别', minWidth: 60, formatter: this.formatSex},
        // {prop: 'phone', label: '手机', minWidth: 120},
        {prop: 'email', label: '邮箱', minWidth: 120},
        {prop: 'avatar', label: '头像', minWidth: 144, imgFlag: true},
        {prop: 'createTime', label: '创建时间', minWidth: 120}
      ],
      roleList: [],
      // 默认不显示弹出框
      dialogFormVisible: false,
      operation: true, // true:新增, false:编辑
      editLoading: false, // 保存表单时loading框
      // 新增编辑界面数据
      dataForm: {},
      // 表单检验规则
      dataFormRules: {
        username: [{required: true, message: '请输入登录用户名', trigger: 'blur'}],
        nickName: [{required: true, message: '请输入真实姓名', trigger: 'blur'}],
        password: [{required: true, message: '请设置新密码', trigger: 'blur'}],
        roleIds: [{required: true, message: '请选择用户角色', trigger: 'change'}]
      }
    }
  },
  computed: {},
  mounted: function () {
    // 【API请求】----获取角色信息列表
    this.$api.getRoleList({pageNum: 1, pageSize: 1000}).then((res) => {
      console.log("res",res)
      const arrayTemp = []
      res.data.content.forEach(item => {
        arrayTemp.push({value: item.id, text: item.roleName})
      })
      this.roleList = arrayTemp
    }).catch((res) => {
      console.log(res);
      this.$message({message: '角色列表获取失败', type: 'error'})
    })
  },
  created() {
    this.getList()
    // this.getOrganList()
  },
  methods: {
    options,

    // 格式化性别
    formatSex: function (row) {
      if (row.sex == '1') {
        return '男'
      } else if (row.sex == '0') {
        return '女'
      } else {
        return '未知'
      }
    },
    // 获取表格用户数据
    getList() {
      this.listLoading = true
      // 【API请求】----获取用户列表数据
      this.$api.getSysUserList(this.pageRequest).then(response => {
        console.log("response",response)
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false
      }).catch((res) => {
        console.log('请求异常', res);
        this.listLoading = false;
      })
    },
    // 表格数据筛选
    handleFilter() {
        this.pageRequest = {
            pageNum: 1,
            pageSize: 10,
        }
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },
    // 【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true
      this.initDataForm()
      this.dialogFormVisible = true
      this.checkedIds = []
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false
      })
    },
    // 【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      console.log(row)
      this.operation = false
      // 编辑表单字段赋值
      this.dataForm = {
        id: row.id,
        username: row.username,
        realname: row.realname,
        sex: row.sex,
        phone: row.phone,
        email: row.email,
        organId: row.organId,
        organName: '',
        avatar: row.avatar,
        roleIds: []
      }

      // 【API请求】----根据用户id 获取关联的角色ids
      this.$api.getRolesIdByUid({id: row.id}).then(response => {
        this.dataForm.roleIds = response.data
      })

      // this.$refs.formOrganTree.setCheckedKeys([row.organid,'1db57023de1f416bb405a02647313f06']);
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false

        // 给organName赋值
        this.$refs.formOrganTree.setCheckedKeys([row.organId])
        const a = this.$refs.formOrganTree.getCheckedNodes()[0]
        this.dataForm.organName = a.deptName
        this.$refs.selectReport.blur()
      })
    },

    // 表单弹出------点击组织机构树
    handleNodeClick: function (node) {
      if (node.children && node.children.length > 0) {

      } else {
        this.dataForm.organId = node.deptId
        this.dataForm.organName = node.deptName
        this.$refs.selectReport.blur()
      }
    },

    // 保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        } else {
          this.editLoading = true

          const submitEntity = this.dataForm
          submitEntity.roles = this.dataForm.roleIds.join(',')
          delete this.dataForm.roleIds
          // 【API请求】----保存数据
          this.$api.saveUserInfo(submitEntity).then(() => {
            this.editLoading = false// 关闭loading框
            this.dialogFormVisible = false// 关闭表单页面
            this.initDataForm()// 重置表单数据
            this.getList()// 重新获取表格数据
            this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
          })
        }
      })
    },
    // 【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        // 【API请求】---- 删除数据
        this.$api.deleteUser({ids: row.id}).then(() => {
          this.$message({message: '操作成功', type: 'success'})
            this.pageRequest.pageNum = 1
          this.getList()
        })
      }).catch(() => {
      })
    },

    // 初始化表单数据，重新渲染
    initDataForm() {
      this.dataForm = {
        id: '',
        username: '',
        realname: '',
        sex: '',
        phone: '',
        email: '',
        organId: '',
        organName: '',
        userPhoto: '',
        roleIds: []
      }
    },
    // 关闭表单弹出框
    closeDialog() {
      this.initDataForm()
      // this.$refs.formOrganTree.setCheckedKeys([])
      this.dialogFormVisible = false
    }

  }
}
</script>
<style>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
